package com.zbkj.admin.controller;


import cn.hutool.json.JSONObject;
import com.zbkj.admin.constants.UserConstants;
import com.zbkj.admin.model.user.User;
import com.zbkj.admin.model.user.UserToken;
import com.zbkj.admin.request.*;
import com.zbkj.admin.response.FrontLoginConfigResponse;
import com.zbkj.admin.response.LoginResponse;
import com.zbkj.admin.result.CommonResult;
import com.zbkj.admin.service.SystemConfigService;
import com.zbkj.admin.service.UserService;
import com.zbkj.admin.service.UserTokenService;
import com.zbkj.admin.service.WechatService;
import com.zbkj.admin.util.RedisUtil;
import com.zbkj.admin.vo.WeChatAuthorizeLoginUserInfoVo;
import com.zbkj.admin.front.service.LoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * 用户登陆 前端控制器
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/front/login")
@Tag(name = "用户 -- 登录注册")
public class LoginFrontController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private UserService userService;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private RedisUtil redisUtil;

    @Operation(summary = "获取公众号用户token")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public CommonResult<LoginResponse> getUserInfo(@RequestParam("openid") String openid) {
        return CommonResult.success(loginService.getUserInfo(openid));
    }

    @Operation(summary = "获取公众号用户信息")
    @RequestMapping(value = "/getSnsUserInfo", method = RequestMethod.GET)
    public CommonResult<WeChatAuthorizeLoginUserInfoVo> getSnsUserInfo(@RequestParam("accessToken") String accessToken, @RequestParam("openid") String openid) {
        return CommonResult.success(wechatService.getSnsUserInfo(accessToken, openid));
    }

    @Operation(summary = "获取登录配置")
    @RequestMapping(value = "/config", method = RequestMethod.GET)
    public CommonResult<FrontLoginConfigResponse> getLoginConfig() {
        return CommonResult.success(loginService.getLoginConfig());
    }

    @Operation(summary = "手机号验证码登录")
    @RequestMapping(value = "/mobile/captcha", method = RequestMethod.POST)
    public CommonResult<LoginResponse> phoneCaptchaLogin(@RequestBody @Validated LoginMobileRequest loginRequest) {
        return CommonResult.success(loginService.phoneCaptchaLogin(loginRequest));
    }

    @Operation(summary = "手机号密码登录")
    @RequestMapping(value = "/mobile/password", method = RequestMethod.POST)
    public CommonResult<LoginResponse> phonePasswordLogin(@RequestBody @Validated LoginPasswordRequest loginRequest) {
        return CommonResult.success(loginService.phonePasswordLogin(loginRequest));
    }

    @Operation(summary = "退出")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public CommonResult<String> loginOut(HttpServletRequest request) {
        loginService.loginOut(request);
        return CommonResult.success();
    }

    @Operation(summary = "是否绑定")
    @RequestMapping(value = "/isBinding", method = RequestMethod.GET)
    public CommonResult<Boolean> isBinding() {
        User info = userService.getInfo();
        UserToken tokenByUserId = userTokenService.getTokenByUserId(info.getId(), UserConstants.USER_TOKEN_TYPE_WECHAT);
        if (Objects.isNull(tokenByUserId)) {
            return CommonResult.success(false);
        } else {
            return CommonResult.success(true);
        }
    }

    @Operation(summary = "获取微信code")
    @RequestMapping(value = "/getCode", method = RequestMethod.GET)
    public CommonResult<JSONObject> getCode(@RequestParam("sign") String sign) throws UnsupportedEncodingException {
//        switch (sign) {
//            case PayConstants.PAY_CHANNEL_WECHAT_PUBLIC -> {
//                return CommonResult.success(wechatApi.getCode(systemConfigService.getValueByKey(WeChatConstants.WECHAT_PUBLIC_APPID), systemConfigService.getValueByKey(WeChatConstants.WECHAT_PAY_PUBLIC_KEY),
//                        URLEncoder.encode("https://prodapi.huikexin.fun/pages/goods/goods_details/index", StandardCharsets.UTF_8)));
//            }
//            case PayConstants.PAY_CHANNEL_WECHAT_MINI -> {
//                return CommonResult.success(wechatApi.getCode(systemConfigService.getValueByKey(WeChatConstants.WECHAT_MINI_APPID), systemConfigService.getValueByKey(WeChatConstants.WECHAT_PAY_MINI_KEY)
//                        , URLEncoder.encode("https://prodapi.huikexin.fun/pages/goods/goods_details/index", StandardCharsets.UTF_8)));
//            }
//        }
        return CommonResult.failed();
    }

    @Operation(summary = "发送短信登录验证码")
    @RequestMapping(value = "/send/code", method = RequestMethod.POST)
    public CommonResult<String> sendCode(@RequestBody @Validated SendCodeRequest request) {
        if (loginService.sendLoginCode(request.getPhone())) {
            return CommonResult.success("发送成功");
        }
        return CommonResult.failed("发送失败");
    }

    @Operation(summary = "微信公众号号授权登录")
    @RequestMapping(value = "/wechat/public", method = RequestMethod.POST)
    public CommonResult<LoginResponse> wechatPublicLogin(@RequestBody @Validated WechatPublicLoginRequest request) {
        return CommonResult.success(loginService.wechatPublicLogin(request));
    }

    @Operation(summary = "微信登录小程序授权登录")
    @RequestMapping(value = "/wechat/routine", method = RequestMethod.POST)
    public CommonResult<LoginResponse> wechatRoutineLogin(@RequestBody @Validated RegisterThirdUserRequest request) {
        return CommonResult.success(loginService.wechatRoutineLogin(request));
    }

    @Operation(summary = "微信注册绑定手机号")
    @RequestMapping(value = "/wechat/register/binding/phone", method = RequestMethod.POST)
    public CommonResult<LoginResponse> wechatRegisterBindingPhone(@RequestBody @Validated WxBindingPhoneRequest request) {
        return CommonResult.success(loginService.wechatRegisterBindingPhone(request));
    }

    @Operation(summary = "微信登录App授权登录")
    @RequestMapping(value = "/wechat/app/login", method = RequestMethod.POST)
    public CommonResult<LoginResponse> wechatAppLogin(@RequestBody @Validated RegisterAppWxRequest request) {
        return CommonResult.success(loginService.wechatAppLogin(request));
    }

    @Operation(summary = "ios登录")
    @RequestMapping(value = "/ios/login", method = RequestMethod.POST)
    public CommonResult<LoginResponse> ioslogin(@RequestBody @Validated IosLoginRequest loginRequest) {
        return CommonResult.success(loginService.ioslogin(loginRequest));
    }

    @Operation(summary = "校验token是否有效")
    @RequestMapping(value = "/token/is/exist", method = RequestMethod.POST)
    public CommonResult<Boolean> tokenIsExist() {
        return CommonResult.success(loginService.tokenIsExist());
    }

}



